<script setup lang="ts">
import {
  ref,
  reactive,
  onMounted,
  computed,
  nextTick,
  onUnmounted,
  h,
} from "vue";
import * as echarts from "echarts";
import { DynamicTable } from "@/components/DynamicTable";
import { TableColumn, PaginationConfig } from "@/components/DynamicTable/types";
import {
  ElMessage,
  ElMessageBox,
  ElTag,
  ElButton,
  ElDialog,
  ElDrawer,
  ElDescriptions,
  ElDescriptionsItem,
  ElTabs,
  ElTabPane,
  ElTable,
  ElTableColumn,
  ElSelect,
  ElOption,
  ElInput,
  ElRow,
  ElCol,
  ElCard,
  ElDivider,
  ElPagination,
  ElAlert,
} from "element-plus";
import { Refresh, Download, Search } from "@element-plus/icons-vue";
import {
  getDepartmentRanking,
  getDepartmentDetail,
  compareDepartments,
  getDepartmentTrend,
  getDepartmentTrendAll,
  saveDepartmentSnapshot,
  queryDepartmentAssets,
} from "../servers";

const loading = ref(false);
const departments = ref<any[]>([]);
const overall = ref<any>({});
const selectedDepartments = ref<any[]>([]);
const tableRef = ref();

// 筛选和排序
const filters = reactive({
  keyword: "",
  sortBy: "rank_asc", // rank_asc | score_asc | score_desc | risk_desc
});

// 部门详情相关
const showDetailDialog = ref(false);
const detailLoading = ref(false);
const currentDepartment = ref<any>(null);
const detailTab = ref("basic"); // basic | dimension | trend | assets
const departmentDetail = ref<any>(null);
const departmentTrend = ref<any>(null);
const departmentAssets = ref<any[]>([]);
const assetsPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 部门对比相关
const showComparison = ref(false);
const comparisonData = ref<any>(null);
const comparisonTrendChart = ref<HTMLDivElement>();
const comparisonDistributionChart = ref<HTMLDivElement>();
const comparisonRadarChart = ref<HTMLDivElement>();
let trendChartInstance: echarts.ECharts | null = null;
let distributionChartInstance: echarts.ECharts | null = null;
let radarChartInstance: echarts.ECharts | null = null;

// 快照相关
const snapshotLoading = ref(false);

// 图表引用（详情弹窗）
const detailRiskPieRef = ref<HTMLDivElement>();
const detailScoreBarRef = ref<HTMLDivElement>();
const detailRadarRef = ref<HTMLDivElement>();
const detailTrendRef = ref<HTMLDivElement>();
let detailRiskPieChart: echarts.ECharts | null = null;
let detailScoreBarChart: echarts.ECharts | null = null;
let detailRadarChart: echarts.ECharts | null = null;
let detailTrendChart: echarts.ECharts | null = null;

// 表格列配置
const columns = ref<TableColumn[]>([
  {
    label: "排名",
    prop: "rank",
    width: 80,
    align: "center",
    show: true,
  },
  {
    label: "部门名称",
    prop: "department_name",
    minWidth: 200,
    show: true,
  },
  {
    label: "资产数",
    prop: "total_assets",
    width: 100,
    align: "center",
    show: true,
  },
  {
    label: "平均分",
    prop: "average_score",
    width: 100,
    align: "center",
    show: true,
    render: (row) => {
      return h(
        "span",
        { style: { fontWeight: "bold" } },
        parseFloat(row.average_score || 0).toFixed(2)
      );
    },
  },
  {
    label: "高风险率",
    prop: "high_risk_rate",
    width: 120,
    align: "center",
    show: true,
    render: (row) => {
      const rate = parseFloat(row.high_risk_rate || 0);
      const color = rate >= 20 ? "#f5222d" : rate >= 10 ? "#faad14" : "#52c41a";
      return h("span", { style: { color } }, `${rate.toFixed(1)}%`);
    },
  },
  {
    label: "趋势",
    prop: "trend",
    width: 120,
    align: "center",
    show: true,
    render: (row) => {
      const trend = row.trend || "stable";
      const scoreChange = parseFloat(row.score_change || 0);
      const config: Record<string, { icon: string; color: string }> = {
        up: { icon: "↑", color: "#52c41a" },
        down: { icon: "↓", color: "#f5222d" },
        stable: { icon: "→", color: "#d9d9d9" },
      };
      const { icon, color } = config[trend] || config.stable;
      const text =
        scoreChange > 0
          ? `+${scoreChange.toFixed(1)}`
          : scoreChange < 0
          ? scoreChange.toFixed(1)
          : "±0.0";
      return h("span", { style: { color } }, `${icon} ${text}`);
    },
  },
  {
    label: "评级",
    prop: "grade",
    width: 100,
    align: "center",
    show: true,
    render: (row) => {
      const grade = row.grade || "E";
      const gradeDesc = row.grade_desc || "未知";
      const colorMap: Record<string, string> = {
        A: "#52c41a",
        B: "#1890ff",
        C: "#faad14",
        D: "#fa8c16",
        E: "#f5222d",
      };
      return h(
        ElTag,
        {
          type:
            grade === "A"
              ? "success"
              : grade === "B"
              ? "info"
              : grade === "C"
              ? "warning"
              : "danger",
          size: "small",
        },
        `${grade} - ${gradeDesc}`
      );
    },
  },
  {
    label: "操作",
    prop: "action",
    width: 200,
    fixed: "right",
    show: true,
    slot: "action",
  },
]);

// 过滤后的部门列表
const filteredDepartments = computed(() => {
  let result = [...departments.value];

  // 关键词搜索
  if (filters.keyword) {
    result = result.filter((d) => d.department_name?.includes(filters.keyword));
  }

  // 排序
  switch (filters.sortBy) {
    case "rank_asc":
      result.sort((a, b) => (a.rank || 0) - (b.rank || 0));
      break;
    case "score_asc":
      result.sort(
        (a, b) =>
          parseFloat(a.average_score || 0) - parseFloat(b.average_score || 0)
      );
      break;
    case "score_desc":
      result.sort(
        (a, b) =>
          parseFloat(b.average_score || 0) - parseFloat(a.average_score || 0)
      );
      break;
    case "risk_desc":
      result.sort(
        (a, b) =>
          parseFloat(b.high_risk_rate || 0) - parseFloat(a.high_risk_rate || 0)
      );
      break;
  }

  return result;
});

// 获取部门排名列表
const fetchDepartmentRanking = async () => {
  loading.value = true;
  try {
    const { data } = await getDepartmentRanking({});
    if (data) {
      departments.value = data.departments || [];
      overall.value = data.overall || {};
    }
  } catch (e: any) {
    console.error("获取部门排名失败:", e);
    ElMessage.error(e?.message || "获取部门排名失败");
  } finally {
    loading.value = false;
  }
};

// 表格选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedDepartments.value = selection;
  if (selection.length >= 2 && selection.length <= 5) {
    fetchComparisonData();
    showComparison.value = true;
  } else {
    showComparison.value = false;
  }
};

// 获取部门对比数据
const fetchComparisonData = async () => {
  if (selectedDepartments.value.length < 2) return;

  try {
    const departmentNames = selectedDepartments.value.map(
      (d) => d.department_name
    );
    const [compareRes, trendRes] = await Promise.all([
      compareDepartments({
        department_names: departmentNames,
      }),
      getDepartmentTrendAll({
        days: 30,
        top_n: 0, // 不限制，获取所有选中部门的趋势
      }),
    ]);

    if (compareRes.data) {
      comparisonData.value = compareRes.data;
      // 合并趋势数据到对比数据中
      if (trendRes.data) {
        comparisonData.value.trend_data = trendRes.data;
      }
      await nextTick();
      initComparisonCharts();
    }
  } catch (e: any) {
    console.error("获取对比数据失败:", e);
    ElMessage.error(e?.message || "获取对比数据失败");
  }
};

// 初始化对比图表
const initComparisonCharts = () => {
  if (!comparisonData.value) return;

  // 趋势对比图
  if (comparisonTrendChart.value) {
    if (trendChartInstance) {
      trendChartInstance.dispose();
    }
    trendChartInstance = echarts.init(comparisonTrendChart.value);

    const trendData = comparisonData.value.trend_data;
    if (!trendData || !trendData.dates || trendData.dates.length === 0) {
      trendChartInstance.setOption({
        title: { text: "部门评分趋势对比（近30天）", left: "center" },
        graphic: [
          {
            type: "text",
            left: "center",
            top: "middle",
            style: {
              text: "暂无趋势数据，请先保存快照",
              fontSize: 14,
              fill: "#999",
            },
          },
        ],
      });
    } else {
      const departments = comparisonData.value.departments || [];
      const colors = ["#1890ff", "#52c41a", "#faad14", "#f5222d", "#722ed1"];

      const series = departments
        .filter((dept: any) => {
          // 只显示已选中的部门
          return selectedDepartments.value.some(
            (s) => s.department_name === dept.department_name
          );
        })
        .map((dept: any, index: number) => {
          const deptTrend = trendData.departments?.find(
            (d: any) => d.department_name === dept.department_name
          );
          return {
            name: dept.department_name,
            type: "line",
            data: deptTrend?.scores || [],
            smooth: true,
            itemStyle: { color: colors[index % colors.length] },
            lineStyle: { width: 2 },
          };
        });

      trendChartInstance.setOption({
        title: { text: "部门评分趋势对比（近30天）", left: "center" },
        tooltip: { trigger: "axis" },
        legend: {
          data: departments.map((d: any) => d.department_name),
          bottom: 0,
        },
        xAxis: {
          type: "category",
          data: trendData.dates || [],
          axisLabel: {
            formatter: (value: string) => {
              if (value) {
                const date = new Date(value);
                return `${date.getMonth() + 1}/${date.getDate()}`;
              }
              return value;
            },
          },
        },
        yAxis: {
          type: "value",
          min: 0,
          max: 100,
          axisLabel: {
            formatter: "{value} 分",
          },
        },
        series,
      });
    }
  }

  // 风险分布对比图
  if (comparisonDistributionChart.value) {
    if (distributionChartInstance) {
      distributionChartInstance.dispose();
    }
    distributionChartInstance = echarts.init(comparisonDistributionChart.value);

    const departments = comparisonData.value.departments || [];
    const option = {
      title: { text: "部门风险等级分布对比", left: "center" },
      tooltip: { trigger: "axis" },
      legend: {
        data: ["严重", "高危", "中危", "低危", "安全"],
        bottom: 0,
      },
      xAxis: {
        type: "category",
        data: departments.map((d: any) => d.department_name),
        axisLabel: {
          rotate: 45,
          interval: 0,
        },
      },
      yAxis: { type: "value" },
      series: [
        {
          name: "严重",
          type: "bar",
          stack: "risk",
          data: departments.map((d: any) => d.risk_distribution?.critical || 0),
          itemStyle: { color: "#f5222d" },
        },
        {
          name: "高危",
          type: "bar",
          stack: "risk",
          data: departments.map((d: any) => d.risk_distribution?.high || 0),
          itemStyle: { color: "#fa8c16" },
        },
        {
          name: "中危",
          type: "bar",
          stack: "risk",
          data: departments.map((d: any) => d.risk_distribution?.medium || 0),
          itemStyle: { color: "#faad14" },
        },
        {
          name: "低危",
          type: "bar",
          stack: "risk",
          data: departments.map((d: any) => d.risk_distribution?.low || 0),
          itemStyle: { color: "#52c41a" },
        },
        {
          name: "安全",
          type: "bar",
          stack: "risk",
          data: departments.map((d: any) => d.risk_distribution?.safe || 0),
          itemStyle: { color: "#1890ff" },
        },
      ],
    };
    distributionChartInstance.setOption(option);
  }

  // 维度扣分雷达图对比
  if (comparisonRadarChart.value) {
    if (radarChartInstance) {
      radarChartInstance.dispose();
    }
    radarChartInstance = echarts.init(comparisonRadarChart.value);

    const departments = comparisonData.value.departments || [];
    const dimensionNames: Record<string, string> = {
      compliance_status: "合规状态",
      vulnerability_risk: "漏洞风险",
      intelligence_match: "威胁情报",
      high_risk_port: "高危端口",
      local_remote_diff: "本异地差异",
      domain_weight: "域名权重",
    };

    // 获取所有维度
    const allDimensions = new Set<string>();
    departments.forEach((dept: any) => {
      Object.keys(dept.dimension_avg_deductions || {}).forEach((dim) =>
        allDimensions.add(dim)
      );
    });

    const indicator = Array.from(allDimensions).map((dim) => ({
      name: dimensionNames[dim] || dim,
      max: 25,
    }));

    const seriesData = departments.map((dept: any) => ({
      name: dept.department_name,
      value: indicator.map((ind) => {
        const dimCode = Object.keys(dimensionNames).find(
          (k) => dimensionNames[k] === ind.name
        );
        return dept.dimension_avg_deductions?.[dimCode || ""] || 0;
      }),
    }));

    const option = {
      title: { text: "部门维度扣分对比", left: "center" },
      tooltip: { trigger: "item" },
      legend: {
        data: departments.map((d: any) => d.department_name),
        bottom: 0,
      },
      radar: {
        indicator,
        name: {
          fontSize: 14,
          fontWeight: "bold",
          color: "#303133",
        },
        splitArea: {
          areaStyle: {
            color: ["rgba(64, 158, 255, 0.1)", "rgba(64, 158, 255, 0.05)"],
          },
        },
        axisLine: {
          lineStyle: {
            color: "#409EFF",
            width: 1,
          },
        },
        splitLine: {
          lineStyle: {
            color: "#409EFF",
            width: 1,
            type: "dashed",
          },
        },
      },
      series: [
        {
          type: "radar",
          data: seriesData,
        },
      ],
    };
    radarChartInstance.setOption(option);
  }
};

// 显示部门详情
const handleShowDetail = async (row: any) => {
  currentDepartment.value = row;
  showDetailDialog.value = true;
  detailTab.value = "basic";
  detailLoading.value = true;

  try {
    // 获取部门详情
    const { data } = await getDepartmentDetail({
      department_name: row.department_name,
    });
    departmentDetail.value = data;

    await nextTick();
    initDetailCharts();
  } catch (e: any) {
    console.error("获取部门详情失败:", e);
    ElMessage.error(e?.message || "获取部门详情失败");
  } finally {
    detailLoading.value = false;
  }
};

// 初始化详情图表
const initDetailCharts = () => {
  if (!departmentDetail.value) return;

  // 风险分布饼图
  if (detailRiskPieRef.value && detailTab.value === "basic") {
    if (detailRiskPieChart) {
      detailRiskPieChart.dispose();
    }
    detailRiskPieChart = echarts.init(detailRiskPieRef.value);

    const dist = departmentDetail.value.risk_distribution || {};
    const option = {
      tooltip: { trigger: "item" },
      legend: { bottom: 0 },
      series: [
        {
          type: "pie",
          radius: ["40%", "70%"],
          data: [
            {
              name: "严重",
              value: dist.critical || 0,
              itemStyle: { color: "#f5222d" },
            },
            {
              name: "高危",
              value: dist.high || 0,
              itemStyle: { color: "#fa8c16" },
            },
            {
              name: "中危",
              value: dist.medium || 0,
              itemStyle: { color: "#faad14" },
            },
            {
              name: "低危",
              value: dist.low || 0,
              itemStyle: { color: "#52c41a" },
            },
            {
              name: "安全",
              value: dist.safe || 0,
              itemStyle: { color: "#1890ff" },
            },
          ],
        },
      ],
    };
    detailRiskPieChart.setOption(option);
  }

  // 分数段分布柱状图
  if (detailScoreBarRef.value && detailTab.value === "basic") {
    if (detailScoreBarChart) {
      detailScoreBarChart.dispose();
    }
    detailScoreBarChart = echarts.init(detailScoreBarRef.value);

    const scoreDist = departmentDetail.value.score_distribution || {};
    const option = {
      tooltip: { trigger: "axis" },
      xAxis: {
        type: "category",
        data: ["0-40", "40-60", "60-80", "80-90", "90-100"],
      },
      yAxis: { type: "value" },
      series: [
        {
          type: "bar",
          data: [
            scoreDist["0-40"] || 0,
            scoreDist["40-60"] || 0,
            scoreDist["60-80"] || 0,
            scoreDist["80-90"] || 0,
            scoreDist["90-100"] || 0,
          ],
          itemStyle: {
            color: (params: any) => {
              const colors = [
                "#f5222d",
                "#fa8c16",
                "#faad14",
                "#52c41a",
                "#1890ff",
              ];
              return colors[params.dataIndex] || "#999";
            },
          },
        },
      ],
    };
    detailScoreBarChart.setOption(option);
  }

  // 维度扣分雷达图
  if (detailRadarRef.value && detailTab.value === "dimension") {
    if (detailRadarChart) {
      detailRadarChart.dispose();
    }
    detailRadarChart = echarts.init(detailRadarRef.value);

    const deductions = departmentDetail.value.dimension_avg_deductions || {};
    const dimensionNames: Record<string, string> = {
      compliance_status: "合规状态",
      vulnerability_risk: "漏洞风险",
      intelligence_match: "威胁情报",
      high_risk_port: "高危端口",
      local_remote_diff: "本异地差异",
      domain_weight: "域名权重",
    };

    const indicator = Object.keys(deductions).map((key) => ({
      name: dimensionNames[key] || key,
      max: 25,
    }));

    const option = {
      tooltip: { trigger: "item" },
      radar: {
        indicator,
        name: {
          fontSize: 14,
          fontWeight: "bold",
          color: "#303133",
        },
        splitArea: {
          areaStyle: {
            color: ["rgba(64, 158, 255, 0.1)", "rgba(64, 158, 255, 0.05)"],
          },
        },
        axisLine: {
          lineStyle: {
            color: "#409EFF",
            width: 1,
          },
        },
        splitLine: {
          lineStyle: {
            color: "#409EFF",
            width: 1,
            type: "dashed",
          },
        },
      },
      series: [
        {
          type: "radar",
          data: [
            {
              value: Object.values(deductions),
              name: departmentDetail.value.department_name,
              itemStyle: {
                color: "#ff7875",
              },
              areaStyle: {
                color: "rgba(255, 120, 117, 0.3)",
              },
            },
          ],
        },
      ],
    };
    detailRadarChart.setOption(option);
  }
};

// 切换详情Tab
const handleDetailTabChange = async (tab: string) => {
  detailTab.value = tab;

  if (tab === "trend") {
    // 获取趋势数据
    if (currentDepartment.value) {
      try {
        detailLoading.value = true;
        const { data } = await getDepartmentTrend({
          department_name: currentDepartment.value.department_name,
          days: 30,
        });
        departmentTrend.value = data;
        await nextTick();
        initTrendChart();
      } catch (e: any) {
        console.error("获取趋势数据失败:", e);
        ElMessage.error(e?.message || "获取趋势数据失败");
      } finally {
        detailLoading.value = false;
      }
    }
  } else if (tab === "assets") {
    // 获取资产列表
    if (currentDepartment.value) {
      await fetchDepartmentAssets();
    }
  } else {
    await nextTick();
    initDetailCharts();
  }
};

// 初始化趋势图
const initTrendChart = () => {
  if (!detailTrendRef.value || !departmentTrend.value) return;

  if (detailTrendChart) {
    detailTrendChart.dispose();
  }
  detailTrendChart = echarts.init(detailTrendRef.value);

  const trendData = departmentTrend.value.trend_data || [];
  if (trendData.length === 0) {
    detailTrendChart.setOption({
      graphic: [
        {
          type: "text",
          left: "center",
          top: "middle",
          style: {
            text: departmentTrend.value.message || "暂无历史数据",
            fontSize: 14,
            fill: "#999",
          },
        },
      ],
    });
    return;
  }

  const option = {
    title: {
      text: `${departmentTrend.value.department_name} - 趋势分析`,
      left: "center",
    },
    tooltip: { trigger: "axis" },
    legend: { data: ["平均分", "排名"], bottom: 0 },
    xAxis: {
      type: "category",
      data: trendData.map((d: any) => d.date),
    },
    yAxis: [
      {
        type: "value",
        name: "平均分",
        min: 0,
        max: 100,
        position: "left",
      },
      {
        type: "value",
        name: "排名",
        inverse: true,
        position: "right",
      },
    ],
    series: [
      {
        name: "平均分",
        type: "line",
        yAxisIndex: 0,
        data: trendData.map((d: any) => parseFloat(d.average_score || 0)),
        smooth: true,
        itemStyle: { color: "#1890ff" },
        areaStyle: {
          color: {
            type: "linear",
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: "rgba(24, 144, 255, 0.3)" },
              { offset: 1, color: "rgba(24, 144, 255, 0.1)" },
            ],
          },
        },
      },
      {
        name: "排名",
        type: "line",
        yAxisIndex: 1,
        data: trendData.map((d: any) => d.rank || 0),
        smooth: true,
        itemStyle: { color: "#52c41a" },
      },
    ],
  };
  detailTrendChart.setOption(option);
};

// 获取部门资产列表
const fetchDepartmentAssets = async () => {
  if (!currentDepartment.value) return;

  detailLoading.value = true;
  try {
    const { data } = await queryDepartmentAssets({
      department_name: currentDepartment.value.department_name,
      page: assetsPagination.currentPage,
      page_size: assetsPagination.pageSize,
      order_by: "total_score",
      order_direction: "asc",
    });

    if (data) {
      departmentAssets.value = data.items || [];
      assetsPagination.total = data.total || 0;
    }
  } catch (e: any) {
    console.error("获取资产列表失败:", e);
    ElMessage.error(e?.message || "获取资产列表失败");
  } finally {
    detailLoading.value = false;
  }
};

// 资产列表分页
const handleAssetsPageChange = (page: number) => {
  assetsPagination.currentPage = page;
  fetchDepartmentAssets();
};

const handleAssetsSizeChange = (size: number) => {
  assetsPagination.pageSize = size;
  assetsPagination.currentPage = 1;
  fetchDepartmentAssets();
};

// 保存排名快照
const handleSaveSnapshot = async () => {
  try {
    await ElMessageBox.confirm("确定要保存当前排名快照吗？", "确认保存", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    snapshotLoading.value = true;
    const { data } = await saveDepartmentSnapshot({});
    if (data?.success) {
      ElMessage.success(`已成功保存 ${data.saved_count || 0} 个部门的快照`);
    } else {
      ElMessage.error("保存快照失败");
    }
  } catch (e: any) {
    if (e !== "cancel") {
      console.error("保存快照失败:", e);
      ElMessage.error(e?.message || "保存快照失败");
    }
  } finally {
    snapshotLoading.value = false;
  }
};

// 导出数据
const handleExport = () => {
  ElMessage.info("导出功能开发中...");
};

// 获取风险等级显示
const getRiskLevelDisplay = (level: string) => {
  const levelMap: Record<
    string,
    { label: string; icon: string; color: string }
  > = {
    critical: { label: "严重", icon: "🔴", color: "#f5222d" },
    high: { label: "高危", icon: "🟠", color: "#fa8c16" },
    medium: { label: "中危", icon: "🟡", color: "#faad14" },
    low: { label: "低危", icon: "🟢", color: "#52c41a" },
    safe: { label: "安全", icon: "🔵", color: "#1890ff" },
  };
  return levelMap[level] || { label: level, icon: "", color: "#666" };
};

// 组件卸载时清理图表
onUnmounted(() => {
  if (trendChartInstance) {
    trendChartInstance.dispose();
    trendChartInstance = null;
  }
  if (distributionChartInstance) {
    distributionChartInstance.dispose();
    distributionChartInstance = null;
  }
  if (radarChartInstance) {
    radarChartInstance.dispose();
    radarChartInstance = null;
  }
  if (detailRiskPieChart) {
    detailRiskPieChart.dispose();
    detailRiskPieChart = null;
  }
  if (detailScoreBarChart) {
    detailScoreBarChart.dispose();
    detailScoreBarChart = null;
  }
  if (detailRadarChart) {
    detailRadarChart.dispose();
    detailRadarChart = null;
  }
  if (detailTrendChart) {
    detailTrendChart.dispose();
    detailTrendChart = null;
  }
});

onMounted(() => {
  fetchDepartmentRanking();
});
</script>

<template>
  <div class="department-risk-page">
    <el-card shadow="never" style="margin-bottom: 20px">
      <div v-if="overall.total_departments" class="overall-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">总部门数:</span>
              <span class="stat-value">{{ overall.total_departments }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">总资产数:</span>
              <span class="stat-value">{{ overall.total_assets }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">平均评分:</span>
              <span class="stat-value">{{
                parseFloat(overall.average_score || 0).toFixed(2)
              }}</span>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <span class="stat-label">高风险资产:</span>
              <span class="stat-value danger">
                {{
                  (overall.risk_distribution?.critical || 0) +
                  (overall.risk_distribution?.high || 0)
                }}
              </span>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!-- 筛选区 -->
    <el-card shadow="never" class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filters.sortBy" placeholder="排序方式" clearable>
            <el-option label="按排名升序" value="rank_asc" />
            <el-option label="按平均分升序" value="score_asc" />
            <el-option label="按平均分降序" value="score_desc" />
            <el-option label="按高风险率降序" value="risk_desc" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索部门名称"
            clearable
            :prefix-icon="Search"
          />
        </el-col>
        <el-col :span="4">
          <el-button
            type="primary"
            :icon="Refresh"
            @click="fetchDepartmentRanking"
            >刷新</el-button
          >
        </el-col>
        <el-col :span="4">
          <el-button :icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 部门排名表格 -->
    <el-card shadow="never" class="ranking-card">
      <template #header>
        <div class="card-header">
          <span>🏢 部门风险排名</span>
          <div>
            <el-button :loading="snapshotLoading" @click="handleSaveSnapshot">
              保存排名快照
            </el-button>
          </div>
        </div>
      </template>

      <DynamicTable
        ref="tableRef"
        :columns="columns"
        :data="filteredDepartments"
        :loading="loading"
        selection-type="multiple"
        @selection-change="handleSelectionChange"
      >
        <template #action="{ row }">
          <el-button
            type="primary"
            link
            size="small"
            @click="handleShowDetail(row)"
          >
            详情
          </el-button>
        </template>
      </DynamicTable>

      <!-- 整体统计信息 -->
    </el-card>

    <!-- 部门对比区 -->
    <el-card
      v-if="showComparison && comparisonData"
      shadow="never"
      class="comparison-card"
    >
      <template #header>
        <div class="card-header">
          <span>
            📊 部门对比 (已选择 {{ selectedDepartments.length }} 个部门):
            {{ selectedDepartments.map((d) => d.department_name).join("、") }}
          </span>
          <el-button
            link
            @click="
              () => {
                showComparison = false;
                selectedDepartments = [];
                tableRef?.clearSelection?.();
              }
            "
          >
            取消对比
          </el-button>
        </div>
      </template>

      <el-row :gutter="20">
        <el-col :span="24">
          <div ref="comparisonTrendChart" style="height: 400px"></div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="24">
          <div ref="comparisonDistributionChart" style="height: 400px"></div>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="24">
          <div ref="comparisonRadarChart" style="height: 400px"></div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 部门详情抽屉 -->
    <el-drawer
      v-model="showDetailDialog"
      :title="`部门详情: ${currentDepartment?.department_name || ''}`"
      size="70%"
      :close-on-click-modal="false"
    >
      <div v-if="departmentDetail" v-loading="detailLoading">
        <el-tabs v-model="detailTab" @tab-change="handleDetailTabChange">
          <!-- Tab1: 基础统计 -->
          <el-tab-pane label="基础统计" name="basic">
            <el-descriptions :column="2" border style="margin-bottom: 20px">
              <el-descriptions-item label="部门名称">
                {{ departmentDetail.department_name }}
              </el-descriptions-item>
              <el-descriptions-item label="排名">
                <el-tag type="warning" size="large"
                  >#{{ departmentDetail.rank }}</el-tag
                >
              </el-descriptions-item>
              <el-descriptions-item label="资产总数">
                {{ departmentDetail.total_assets }}
              </el-descriptions-item>
              <el-descriptions-item label="平均分">
                <span
                  style="font-size: 18px; font-weight: bold; color: #1890ff"
                >
                  {{
                    parseFloat(departmentDetail.average_score || 0).toFixed(2)
                  }}
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="高风险率">
                <span
                  :style="{
                    color:
                      departmentDetail.high_risk_rate >= 20
                        ? '#f5222d'
                        : departmentDetail.high_risk_rate >= 10
                        ? '#faad14'
                        : '#52c41a',
                  }"
                >
                  {{
                    parseFloat(departmentDetail.high_risk_rate || 0).toFixed(1)
                  }}%
                </span>
              </el-descriptions-item>
              <el-descriptions-item label="评级">
                <el-tag
                  :type="
                    departmentDetail.grade === 'A'
                      ? 'success'
                      : departmentDetail.grade === 'B'
                      ? 'info'
                      : departmentDetail.grade === 'C'
                      ? 'warning'
                      : 'danger'
                  "
                  size="large"
                >
                  {{ departmentDetail.grade }} -
                  {{ departmentDetail.grade_desc }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-card shadow="never">
                  <template #header>
                    <div class="card-header">风险等级分布</div>
                  </template>
                  <div ref="detailRiskPieRef" style="height: 300px"></div>
                </el-card>
              </el-col>
              <el-col :span="12">
                <el-card shadow="never">
                  <template #header>
                    <div class="card-header">分数段分布</div>
                  </template>
                  <div ref="detailScoreBarRef" style="height: 300px"></div>
                </el-card>
              </el-col>
            </el-row>
          </el-tab-pane>

          <!-- Tab2: 维度分析 -->
          <el-tab-pane label="维度分析" name="dimension">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">各维度平均扣分分析</div>
              </template>
              <div ref="detailRadarRef" style="height: 400px"></div>
            </el-card>

            <el-card shadow="never" style="margin-top: 20px">
              <template #header>
                <div class="card-header">维度扣分详情</div>
              </template>
              <el-table
                :data="
                  Object.entries(departmentDetail.dimension_deductions || {})
                "
                border
              >
                <el-table-column label="维度" width="150">
                  <template #default="{ row }">
                    {{
                      {
                        compliance_status: "合规状态",
                        vulnerability_risk: "漏洞风险",
                        intelligence_match: "威胁情报",
                        high_risk_port: "高危端口",
                        local_remote_diff: "本异地差异",
                        domain_weight: "域名权重",
                      }[row[0]] || row[0]
                    }}
                  </template>
                </el-table-column>
                <el-table-column label="总扣分" width="120" align="center">
                  <template #default="{ row }">
                    {{ row[1]?.total_deduction?.toFixed(2) || 0 }}
                  </template>
                </el-table-column>
                <el-table-column label="影响资产数" width="120" align="center">
                  <template #default="{ row }">
                    {{ row[1]?.asset_count || 0 }}
                  </template>
                </el-table-column>
                <el-table-column label="平均扣分" align="center">
                  <template #default="{ row }">
                    {{
                      departmentDetail.dimension_avg_deductions?.[
                        row[0]
                      ]?.toFixed(2) || 0
                    }}
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </el-tab-pane>

          <!-- Tab3: 趋势分析 -->
          <el-tab-pane label="趋势分析" name="trend">
            <div v-if="departmentTrend">
              <div v-if="departmentTrend.data_points === 0" class="empty-trend">
                <el-alert
                  :title="departmentTrend.message || '暂无历史数据'"
                  type="info"
                  :closable="false"
                />
                <p style="margin-top: 20px; color: #909399">
                  提示：请先调用快照接口保存历史数据才能查看趋势分析
                </p>
              </div>
              <div v-else>
                <el-card shadow="never" style="margin-bottom: 20px">
                  <template #header>
                    <div class="card-header">趋势摘要</div>
                  </template>
                  <el-descriptions :column="3" border>
                    <el-descriptions-item label="当前排名">
                      #{{ departmentTrend.trend_summary?.current_rank }}
                    </el-descriptions-item>
                    <el-descriptions-item label="当前分数">
                      {{
                        departmentTrend.trend_summary?.current_score?.toFixed(2)
                      }}
                    </el-descriptions-item>
                    <el-descriptions-item label="趋势方向">
                      <el-tag
                        :type="
                          departmentTrend.trend_summary?.trend_direction ===
                          'improving'
                            ? 'success'
                            : departmentTrend.trend_summary?.trend_direction ===
                              'declining'
                            ? 'danger'
                            : 'info'
                        "
                      >
                        {{
                          departmentTrend.trend_summary?.trend_direction ===
                          "improving"
                            ? "上升"
                            : departmentTrend.trend_summary?.trend_direction ===
                              "declining"
                            ? "下降"
                            : "稳定"
                        }}
                      </el-tag>
                    </el-descriptions-item>
                    <el-descriptions-item label="排名变化">
                      {{
                        departmentTrend.trend_summary?.total_rank_change > 0
                          ? `上升 ${departmentTrend.trend_summary.total_rank_change} 位`
                          : departmentTrend.trend_summary?.total_rank_change < 0
                          ? `下降 ${Math.abs(
                              departmentTrend.trend_summary.total_rank_change
                            )} 位`
                          : "无变化"
                      }}
                    </el-descriptions-item>
                    <el-descriptions-item label="分数变化">
                      {{
                        departmentTrend.trend_summary?.total_score_change > 0
                          ? `+${departmentTrend.trend_summary.total_score_change.toFixed(
                              2
                            )}`
                          : departmentTrend.trend_summary?.total_score_change.toFixed(
                              2
                            )
                      }}
                    </el-descriptions-item>
                    <el-descriptions-item label="期间最高分">
                      {{
                        departmentTrend.trend_summary?.highest_score?.toFixed(2)
                      }}
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>

                <el-card shadow="never">
                  <template #header>
                    <div class="card-header">评分趋势图（近30天）</div>
                  </template>
                  <div ref="detailTrendRef" style="height: 400px"></div>
                </el-card>
              </div>
            </div>
          </el-tab-pane>

          <!-- Tab4: 资产列表 -->
          <el-tab-pane label="资产列表" name="assets">
            <el-card shadow="never">
              <template #header>
                <div class="card-header">部门资产列表</div>
              </template>
              <el-table
                :data="departmentAssets"
                border
                stripe
                v-loading="detailLoading"
              >
                <el-table-column prop="asset_ip" label="IP地址" width="150" />
                <el-table-column prop="asset_name" label="资产名称" />
                <el-table-column label="评分" width="100" align="center">
                  <template #default="{ row }">
                    <span style="font-weight: bold">{{
                      parseFloat(row.total_score || 0).toFixed(2)
                    }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="风险等级" width="120" align="center">
                  <template #default="{ row }">
                    <el-tag
                      :type="
                        row.risk_level === 'critical' ||
                        row.risk_level === 'high'
                          ? 'danger'
                          : row.risk_level === 'medium'
                          ? 'warning'
                          : row.risk_level === 'low'
                          ? 'success'
                          : 'info'
                      "
                      size="small"
                    >
                      {{ getRiskLevelDisplay(row.risk_level).icon }}
                      {{ getRiskLevelDisplay(row.risk_level).label }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="last_scored_at"
                  label="最后评分时间"
                  width="180"
                />
              </el-table>
              <el-pagination
                v-model:current-page="assetsPagination.currentPage"
                v-model:page-size="assetsPagination.pageSize"
                :total="assetsPagination.total"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next"
                style="margin-top: 16px"
                @current-change="handleAssetsPageChange"
                @size-change="handleAssetsSizeChange"
              />
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </div>
</template>

<style scoped lang="scss">
.department-risk-page {
  padding: 0;
}

.filter-card,
.ranking-card,
.comparison-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  font-size: 16px;
}

.overall-stats {
  .stat-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;

    .stat-label {
      color: #606266;
      font-size: 14px;
    }

    .stat-value {
      font-size: 18px;
      font-weight: 700;
      color: #303133;

      &.danger {
        color: #f56c6c;
      }
    }
  }
}

.empty-trend {
  text-align: center;
  padding: 40px;
}

@media (max-width: 1400px) {
  .filter-card .el-row .el-col {
    margin-bottom: 12px;
  }
}
</style>
